package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.*;
import com.tanhua.dubbo.server.seriver.IdService;
import com.tanhua.dubbo.server.seriver.TimeLineService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;


@Service(version = "1.0.0")
@Slf4j
public class QuanZiApiImpl implements QuanZiApi {

    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIKE_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Reference(version = "1.0.0")
    private VideoApi videoApi;

    /**
     * 好友圈子
     *
     * @param userId   用户id
     * @param page     当前页数
     * @param pageSize 每一页查询的数据条数
     * @return
     */
    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        //分析：查询好友的动态，实际上查询时间线表

        //创建一个返回对象
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);

        //查询出来按照发布时间倒序
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
        //条件构造器
        Query query = new Query().with(pageable);
        List<TimeLine> timeLines = this.mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);

        //判断为空，直接返回没有查询到数据
        if (CollUtil.isEmpty(timeLines)) {
            //没有查询到数据
            return pageInfo;
        }

        //查到了数据，直接获取到发布者的数据
        //获取时间线列中的发布者所有id
        List<Object> ids = CollUtil.getFieldValues(timeLines, "publishId");
        Query queryPublish = Query.query(Criteria.where("id").in(ids))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(queryPublish, Publish.class);
        //添加到列表中
        pageInfo.setRecords(publishList);

        return pageInfo;
    }

    /**
     * 发布动态
     *
     * @param publish
     * @return
     */
    @Override
    public String savePublish(Publish publish) {
        try {
            //校验publish对象是否为空，空的就直接发布失败
            if (!ObjectUtil.isAllNotEmpty(publish.getUserId(), publish.getText())) {
                //用户id，和文本都为空发布失败
                return null;
            }

            //设置主键id
            publish.setId(ObjectId.get());

            //设置pid自增,因为mongodb里面不能设置自增，只能调用redis
            publish.setPid(this.idService.createId(IdType.PUBLISH));
            //设置当前时间
            publish.setCreated(System.currentTimeMillis());

            //把数据先写到发布表中
            this.mongoTemplate.save(publish);

            //写入相册表,填充资料
            Album album = new Album();
            album.setId(ObjectId.get());
            album.setCreated(System.currentTimeMillis());
            album.setPublishId(publish.getId());
            //添加到相册表
            this.mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

            //写入到时间线表中，用异步来完成
            this.timeLineService.saveTimeLine(publish.getUserId(), publish.getId());

        } catch (Exception e) {
            log.error("发布动态失败 ~ publish= " + publish, e);
        }
        return publish.getId().toHexString();
    }

    /**
     * 推荐圈子
     *
     * @param userId   用户id
     * @param page     当前页数
     * @param pageSize 每一页查询的数据条数
     * @return
     */
    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page, Integer pageSize) {
        //设置显示分页
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //从redis中查找推荐的用户id，结果数据
        String key = "QUANZI_PUBLISH_RECOMMEND_" + userId;
        String data = this.redisTemplate.opsForValue().get(key);
        //判断推荐用户是否为空
        if (StrUtil.isEmpty(data)) {
            return pageInfo;
        }

        //查询到的pid进行分页处理
        List<String> pids = StrUtil.split(data, ',');
        //计算分页
        //[0, 10]
        int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
        int startIndex = startEnd[0]; //开始
        int endIndex = Math.min(startEnd[1], pids.size()); //结束

        List<Long> pidLongList = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            pidLongList.add(Long.valueOf(pids.get(i)));
        }

        if (CollUtil.isEmpty(pidLongList)) {
            //没有查询到数据
            return pageInfo;
        }

        //根据pid查询publish
        Query query = Query.query(Criteria.where("pid").in(pidLongList))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(query, Publish.class);
        if (CollUtil.isEmpty(publishList)) {
            //没有查询到数据
            return pageInfo;
        }

        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    /**
     * 根据id查询发布人的动态
     *
     * @param id 动态id
     * @return
     */
    @Override
    public Publish queryPublishById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id), Publish.class);
    }

    /**
     * 点赞或喜欢
     *
     * @param userId      用户id
     * @param publishId   发布表id
     * @param commentType 接收的类型
     * @return
     */
    @Override
    public Boolean likeOrLoveComment(Long userId, String publishId, CommentType commentType) {
        //判断该用户是否已经点赞或喜欢，如果已经点赞或喜欢就直接返回
        if (this.queryUserIsLikeOrLove(userId, publishId, commentType)) {
            return false;
        }

        //用户没有点赞，保存Comment数据
        Boolean result = this.saveComment(userId, publishId, commentType, null);
        if (!result) {
            //保存失败
            return false;
        }

        //修改redis中的点赞数以及是否点赞
        String redisKey = this.getCommentRedisKey(publishId);
        //修改点赞数/喜欢数
        String hashKey = commentType.toString();
        //自增1
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

        //标记是否点赞/是否喜欢
        String userHashKey = this.getCommentUserRedisKey(userId, commentType);
        this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");
        return true;
    }

    /**
     * 用户是否点赞或喜欢的前缀
     *
     * @param userId      用户id
     * @param commentType 接收到的类型
     * @return
     */
    private String getCommentUserRedisKey(Long userId, CommentType commentType) {
        String key = "";
        switch (commentType) {
            case LIKE:
                //用户是否点赞的前缀
                key = COMMENT_USER_LIKE_REDIS_KEY_PREFIX + userId;
                break;
            case LOVE:
                //用户是否喜欢的前缀
                key = COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
                break;
            default:
                break;
        }
        return key;
    }

    /**
     * 取消点赞或取消喜欢
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean disLikeOrLoveComment(Long userId, String publishId, CommentType commentType) {
        //判断用户是否已经点赞或喜欢，如果没有点赞或喜欢就返回
        if (!this.queryUserIsLikeOrLove(userId, publishId, commentType)) {
            return false;
        }

        //删除评论数据
        Boolean result = this.removeComment(userId, publishId, commentType);
        if (!result) {
            return false;
        }
        //修改Redis中的数据

        //修改点赞数或喜欢
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = commentType.toString();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);

        //用户是否点赞或喜欢
        String userHashKey = this.getCommentUserRedisKey(userId, commentType);
        this.redisTemplate.opsForHash().delete(redisKey, userHashKey);

        return true;
    }

    //修改点赞数
    private String getCommentRedisKey(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    /**
     * 查询数量
     *
     * @param publishId
     * @return
     */
    @Override
    public Long getCommenCount(String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType())
        );
        return this.mongoTemplate.count(query, Comment.class);
    }

    /**
     * 查询评论
     *
     * @param publishId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Comment> queryCommentList(String publishId, Integer page, Integer pageSize) {
        //设置评论按照时间正序排列
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc("created")));

        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.COMMENT.getType())).with(pageRequest);
        //获取到评论id
        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);

        //封装数据
        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(commentList);

        return pageInfo;
    }

    /**
     * 发表评论
     *
     * @param userId
     * @param publishId
     * @param content
     * @return
     */
    @Override
    public Boolean saveComment(Long userId, String publishId, String content) {
        return this.saveComment(userId, publishId, CommentType.COMMENT, content);
    }

    /**
     * 查询点赞数或喜欢数
     *
     * @param publishId
     * @return
     */
    @Override
    public Long queryCommenCount(String publishId, CommentType commentType) {
        //首先从redis中命中，如果命中的话就返回，没有命中就查询Mongodb
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = commentType.toString();
        Object value = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)) {
            return Convert.toLong(value);
        }
        //查询count
        Long count = this.getCommenCount(publishId, commentType);

        //存储到redis中
        this.redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(count));

        return count;
    }

    /**
     * 查询用户是否点赞或喜欢该动态
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean queryUserIsLikeOrLove(Long userId, String publishId, CommentType commentType) {
        //从redis中查询数据
        String redisKey = this.getCommentRedisKey(publishId);
        String userHashKey = this.getCommentUserRedisKey(userId, commentType);
        Object data = this.redisTemplate.opsForHash().get(redisKey, userHashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return StrUtil.equals(Convert.toStr(data), "1");
        }

        //查询Mongodb，确定是否已经点赞
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(commentType.getType())
        );

        long count = this.mongoTemplate.count(query, Comment.class);
        if (count == 0) {
            return false;
        }

        //写入到redis中
        //标记用户已经喜欢
        this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }


    /**
     * 保存Comment评论表
     *
     * @param userId
     * @param publishId
     * @param commentType
     * @param content
     * @return
     */
    private Boolean saveComment(Long userId, String publishId,
                                CommentType commentType, String content) {
        try {
            Comment comment = new Comment();
            comment.setId(ObjectId.get());
            comment.setUserId(userId);
            comment.setPublishId(new ObjectId(publishId));
            // 评论类型
            comment.setCommentType(commentType.getType());
            // 内容
            comment.setContent(content);
            comment.setCreated(System.currentTimeMillis());

            Publish publish = this.queryPublishById(publishId);
            if (ObjectUtil.isNotEmpty(publish)) {
                comment.setPublishUserId(publish.getUserId());
            } else {
                //查询评论
                Comment myComment = this.queryCommentById(publishId);
                if (ObjectUtil.isNotEmpty(myComment)) {
                    comment.setPublishUserId(myComment.getUserId());
                } else {
                    //查询小视频
                    Video video = this.videoApi.queryVideoById(publishId);
                    if (ObjectUtil.isNotEmpty(video)) {
                        comment.setPublishUserId(video.getUserId());
                    } else {
                        // 其他情况，直接返回
                        return false;
                    }
                }
            }
            this.mongoTemplate.save(comment);
            return true;
        } catch (Exception e) {
            log.error("保存Comment出错~ userId = " + userId + ", publishId = " + publishId + ", commentType = " + commentType, e);
        }

        return false;
    }

    /**
     * 根据id查询Comment对象
     *
     * @param id
     * @return
     */
    private Comment queryCommentById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id), Comment.class);
    }

    /**
     * 删除评论数据
     *
     * @param userId
     * @param publishId
     * @param commentType
     * @return
     */
    private Boolean removeComment(Long userId, String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType())
        );
        //大于0直接删除成功
        return this.mongoTemplate.remove(query, Comment.class).getDeletedCount() > 0;
    }


    /**
     * 查询评论数
     *
     * @param publishId
     * @return
     */
    @Override
    public Long queryCommentCount1(String publishId) {
        return this.getCommenCount(publishId, CommentType.COMMENT);
    }


    /**
     * 查询对我的评论喜欢点赞消息列表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @param commentType
     * @return
     */
    @Override
    public PageInfo<Comment> queryCommentListByUser(Long userId, Integer page, Integer pageSize, CommentType commentType) {
        //分页查询，按照时间排序
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        //查询发布动态的用户id
        Query query = new Query(Criteria.where("publishUserId").is(userId).
                and("commentType").is(commentType.getType())).
                with(pageRequest);

        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);

        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(commentList);
        return pageInfo;
    }

    /**
     * 查询相册表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {
        //先分页
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //查询自己的相册表，通过发布时间进行排序
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = new Query().with(pageRequest);
        List<Album> albumList = this.mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);

        //拿到publishId 发布id，然后查询发布表
        List<Object> publishIdList = CollUtil.getFieldValues(albumList, " publishId");

        Query queryPublish = Query.query(Criteria.where("id").in(publishIdList)).with(Sort.by(Sort.Order.desc("created")));
        //拿到发布表所有数据
        List<Publish> publishList = this.mongoTemplate.find(queryPublish, Publish.class);


        //直接填充数据
        pageInfo.setRecords(publishList);
        return pageInfo;
    }
}
